package com.yhq.yhqproject.base.modules.chat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class LbChatService {
//    @Value("${laibo.chat.baseUrl}")
    private String baseUrl;
    @Resource
    private RestTemplate restTemplate;

    //json JSONObject或JSONArray
    public String requestLbChatForResult(String uri, JSON json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set(HttpHeaders.ACCEPT_CHARSET, StandardCharsets.UTF_8.name());
        String url = baseUrl + uri;
        HttpEntity<JSON> requestEntity = new HttpEntity<>(json, headers);
        log.info("LaiBo Chat Request Param: "+json.toJSONString());
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
        String response = responseEntity.getBody();
        if (response != null && response.length() > 0) {
            JSONObject obj = JSON.parseObject(response);
            if (1 == obj.getIntValue("code")) {
                String data = obj.getString("data");
                log.info("LaiBo Chat Response Data: "+data);
                return data;
            }
        }
        throw new RuntimeException("LaiBo AI Response error");
    }

    private String convertUnicode(String input) {
        StringBuilder sb = new StringBuilder();
        int startIndex = 0;
        int index;
        while ((index = input.indexOf("\\u", startIndex)) != -1) {
            sb.append(input, startIndex, index);
            if (index + 5 < input.length()) {
                char unicodeChar = (char) Integer.parseInt(input.substring(index + 2, index + 6), 16);
                sb.append(unicodeChar);
                startIndex = index + 6;
            } else {
                break;
            }
        }
        sb.append(input.substring(startIndex));
        return sb.toString();
    }

}
